<?
global $imagesurl,$imagesdir,$config;

define('LIST3_ALL','[ALL]');

#var_dump($_REQUEST);
$db = &$params["db"];
$search = isset($params["search"])?$params["search"]:array();
$search_method = isset($params["search_method"])?$params["search_method"]:"put";
if (function_exists("surl_link")) { $search_method = "post"; }
@$cols = $params["cols"];
@$orderby = $params["orderby"];
@$orderdir = $params["orderdir"];
@$dsearch = $params["dsearch"];
$table = $params["table"];
$key = isset($params["key"])?$params["key"]:"id";
$actions = isset($params["actions"])?$params["actions"]:array();
@$mactions = $params["mactions"];
$pp = isset($params["pp"])?$params["pp"]:$config["list3.pp"];
$nomatch = isset($params["nomatch"])?$params["nomatch"]:"<p>No items matched your search.</p>";
@$fields = $params["fields"];
@$select = $params["select"];
@$from = $params["from"];
@$where = $params["where"];
$tr_class_fnc = (isset($params["tr_class_fnc"])?$params["tr_class_fnc"]:""); 
$ses = isset($params["session"])?$params["session"]:"list_$table";
$autoid = isset($params["autoid"])?$params["autoid"]:true;

$reset = isset($_REQUEST["reset"])?$_REQUEST["reset"]:0;
if (!isset($_SESSION[$ses]) || $reset) {
    $_SESSION[$ses] = array(
        "orderby"=>$orderby,
        "orderdir"=>$orderdir,
        "start"=>0,
        );
    if ($dsearch) foreach ($dsearch as $k=>$v)
        $_SESSION[$ses][$k] = $v;
    }

if (isset($_REQUEST["search"])) {
    foreach ($search as $k) {
        #HACK: PHP workaround, PHP changes variables with .'s to _'s
        $_SESSION[$ses][$k] = $_REQUEST[str_replace(".","_",$k)];
/*        if ($_SESSION[$ses][$k] == "[ALL]") {
            unset($_SESSION[$ses][$k]);
            }*/
        }
        
    $_SESSION[$ses]["start"] = 0;
    }
foreach (array("orderby","orderdir","start") as $k) if (isset($_REQUEST[$k]))
    $_SESSION[$ses][$k] = $_REQUEST[$k];
$s = $_SESSION[$ses];
$orderby = $s["orderby"];
$orderdir = $s["orderdir"];
$start = intval($s["start"]);

echo "<table class='list'>";

$total_cols = count($cols)+count($actions)+isset($mactions);

inc_inclib("html.php");
if (count($search)) {
    echo "<tr><td colspan=$total_cols class='search'>";
    echo "<form method=$search_method>";
    echo "<input type='hidden' name='search' value='1'>";
    foreach ($search as $k) {
        $fe = $fields[$k];
        $v = isset($s[$k])?$s[$k]:"";
        echo "{$fe["title"]}: ";
        switch ($fe["type"]) {
            case "lookup":
            case "select":
                $o = array(LIST3_ALL=>"-- All --");
                foreach ($fe["options"] as $kk=>$vv) $o[$kk]=$vv;
                echo html_option_array("select",$k,$o,$v);
                break;
            default:
                echo "<input type='text' name='$k' value=\"".htmlentities($v)."\" size=16>";
                break;
            }
        echo "&nbsp; ";
        }
    echo " <input type='submit' value='Search'></form>";
    }

if (!isset($select)) $select = "*";
if(!isset($from)) $from = "`$table`";
if (!isset($where)) $where = "1=1";

$query = "";
foreach ($search as $k) {
    $fe = $fields[$k];
    $default = $fe["type"] == "select"?LIST3_ALL:"";
    $v = isset($s[$k])?$s[$k]:$default;
    if (isset($fe["special"]) && $fe["special"] == 1) { continue; }
    switch ($fe["type"]) {
        case "lookup":
            if ($v != "") {
                $from.=",{$fe["table"]}";
                $query.=" and {$fe["table"]}.{$fe["one"]} = $table.$key".
                    " and {$fe["table"]}.{$fe["many"]} = ".$db->sqlstring($v);
                }
            break;
        case "select":
            if ($v != LIST3_ALL) {
                if ($v != "") {
                    $query.=" and $k = ".$db->sqlstring($v);
                } else {
                    $query .= " and $k is null "; 
                    }
                }
            break;
        case "skip":
            break;
        default:
            if ($v != "") {
                $query.=" and $k like ".$db->sqlstring("%$v%");
                }
            break;
        }
    }

$query = "from $from where $where $query";
#echo $query;

function list_sqlalias($v) { return preg_replace("/[^a-zA-Z._]/","",$v); }
$order = list_sqlalias($orderby)." ".list_sqlalias($orderdir);


if ($pp) {
    $e = $db->query1("select count(*) as cnt $query");
    $cnt = $e["cnt"];
    $r = $db->query("select $select $query order by $order limit $start,$pp",true,DB_ERRORS_DIE,$autoid);
    } else {
    $r = $db->query("select $select $query order by $order",true,DB_ERRORS_DIE,$autoid);
    }
    
if (!count($r)) {
    echo $nomatch;
    echo "</table>";
    return 0;
    }
    
if(file_exists("$imagesdir/icons/sortasc.gif")) {
    $icons = array(
        "asc"=>"<img src='$imagesurl/icons/sortasc.gif' border=0 align=absmiddle>",
        "desc"=>"<img src='$imagesurl/icons/sortdesc.gif' border=0 align=absmiddle>",
        );
    } else {
    $icons = array(
        "asc"=>"<span style='font-family: Webdings'>5</span>",
        "desc"=>"<span style='font-family: Webdings'>6</span>",
        );
    }
$space = "&nbsp;";

$aicons = array();
foreach ($actions as $k=>$a) {
    $img = strtolower($k);
    $img = preg_replace("/[^a-z0-9_]/","_",$img);
    if (file_exists("$imagesdir/icons/$img.gif"))
        $v = "<img src='$imagesurl/icons/$img.gif' border=0>";
        else
        $v=$k;
    $aicons[$k]=$v;
    }

function list_action($id,$e,$a) {
    $a = str_replace("%%",$id,$a);
    preg_match_all("/\\\$(\w+)/",$a,$m);
    foreach ($m[0] as $nn=>$kk)
        $a=str_replace($kk,$e[$m[1][$nn]],$a);
/*    if (stripos($a,"javascript:")!==false) {
        $a = str_replace("javascript:","",$a);
        return "onclick='$a' href='#'";
        }*/
    if (substr($a,0,11) == 'javascript:') { return "href='$a'"; }
    return "href=\"$a\"";
    }

if ($mactions) echo "<form id='list_form' action='#' method='post'>";
#echo "<p><table class='list'><tr>";
echo "<tr>";
if ($mactions) echo "<th>&nbsp;";
foreach ($cols as $k) {
    $fe = $fields[$k];
    $title = $fe["title"];
    $title = str_replace(" ","&nbsp;",$title);

    $class = $orderby==$k?"s":"";
    echo "<th align=center class='$class'><nobr>";
    #echo $space;
    $dir = ($orderby == $k?($orderdir=="asc"?"desc":"asc"):"asc");
    if ($orderby == $k) $title.="&nbsp;".$icons[$orderdir];
    if ((isset($fe["orderby"])?$fe["orderby"]:1)==1) {
        echo "<a href=\"?orderby=$k&orderdir=$dir&start=0\">$title</a>";
        } else { 
        echo $title;
        }
    #echo $space;
    echo "</nobr>";
    }
foreach ($actions as $k=>$a)
    echo "<th>".ucfirst($k);
$n=0;
foreach ($r as $e) {
    $id = $e[$key];
    $class = "c".$n%2;
    if ($tr_class_fnc) { $class = $tr_class_fnc($class,$e); }
    $oc = "";
    if ($mactions) {
        $oc = "onclick='document.getElementById(\"$id\").click();'"; 
    }
    echo "<tr class='$class' id='tr-$id' $oc>";
    if ($mactions) { echo "<td><input type='checkbox' name='values[]' value='$id' id='$id' onclick='list_select(this);'>"; }
    foreach ($cols as $k) {
        $fe = $fields[$k];
        $title = $fe["title"];

        $align = isset($fe["output_align"])?$fe["output_align"]:"";
        echo "<td align='$align'>";
        #this is a bit of a hack ... but
        #if the value does exist, just send the record
        #to output functions
        #$v = $e[$k];
        $v = array_key_exists($k,$e)?$e[$k]:$e;
        $v = isset($fe["options"][$v])?$fe["options"][$v]:$v;
        if (isset($fe["output_fnc"]))
            { $v = $fe["output_fnc"]($v); }
            else
            { if ($v=="") $v = "<i>null</i>"; else $v = htmlentities($v); }
        if (isset($fe["action"]))
            echo "<a ".list_action($id,$e,$fe["action"]).">$v</a>";
            else
            echo $v;
        }
    $id = $e[$key];
    foreach ($actions as $k=>$a) {
        echo "<td align='center'><a ".list_action($id,$e,$a).">{$aicons[$k]}</a>";
        }

    $n++;
    echo "\n";
    }
#echo "</table>";
#echo "</p>";


if ($pp && $cnt > $pp) {
    echo "<tr><td colspan=$total_cols class='paging'>";
    #echo "Page: ";
    $min = max(0,$start-$pp*10);
    $max = min($cnt,$start+$pp*10);
    $n = $min/$pp + 1;
    if ($start != 0) {
        $i = $start-$pp;
        echo "<a href=\"?start=$i\">Previous</a> ";
        }
    for ($i=$min; $i<$max; $i+=$pp) {
        echo ($i==$start?"<span class='page'>$n</span>":"<a href=\"?start=$i\" class='page'>$n</a>")." ";
        $n++;
        }
    if ($start < $max-$pp) {
        $i = $start+$pp;
        echo "<a href=\"?start=$i\">Next</a> ";
        }
    }
echo "</table>";

if ($mactions) {
echo "<input type='hidden' id='list_total' value=0>";
echo '<script>
function list_select(t) {
    if (t.checked) n=1; else n=-1;
    e = document.getElementById("list_total");
    e.value = parseInt(e.value)+n;

    if (t.checked) n="s"; else n="";
    e = document.getElementById("tr-"+t.id);
    e.className = e.className.substr(0,2) + n;
    }
function list_selectall() {';
    foreach ($r as $e) {
        $id = $e[$key];
        echo "e = document.getElementById(\"$id\");";
        echo "if (!e.checked) { e.checked = true; list_select(e); }";
        }
    echo '
    }
function list_selectnone() {';
    foreach ($r as $e) {
        $id = $e[$key];
        echo "e = document.getElementById(\"$id\");";
        echo "if (e.checked) { e.checked = false; list_select(e); }";
        }
    echo '
    }
function list_verify() {
    e = document.getElementById("list_total");
    if (e.value < 1) { alert("You must select at least one item to continue."); return(false); }
    return(true);
    }
</script>
';

echo "<p>";
echo "<input type=button value=\"Select All\" onclick='list_selectall();'> ";
echo "<input type=button value=\"Select None\" onclick='list_selectnone();'> ";
foreach ($mactions as $k=>$a) {
    if (function_exists("surl_link")) { $a = surl_link($a); }
    echo "<input type='button' value='".ucfirst($k)." Selected' onclick='if(list_verify()){e=document.getElementById(\"list_form\");e.action=\"".$a."\";e.submit();}'> ";
    }
echo "</p>";
echo "</form>";
}


return 1;
?>
